import React, { useRef, useState,useEffect } from 'react';
import services from '@/services/home';
import { MicroApp } from '@umijs/max';
import { trim,browserRedirect } from '@/utils/format';
import { PageContainer } from '@ant-design/pro-components';
import { loadMicroApp } from 'qiankun';
import { useIntl,useModel,Link,useRequest,history } from '@umijs/max';
import { HeartOutlined,HeartFilled,SearchOutlined } from '@ant-design/icons';

const { getSysUserCollectList,sysUserCollect,deletesysUserCollect} =
  services.UserController;

import { Collapse, message,Empty, Layout, Row,Col,Card,Button,Input,Popover } from 'antd';
const { Panel } = Collapse;
const { Meta } = Card;
const { Search } = Input;

import styles from './index.less';

const HomePage: React.FC = () => {
  const { name,setName,clearCurrentTabList,allToken } = useModel('global');
  const { initialState, setInitialState }:any = useModel('@@initialState');
  const intl = useIntl();
  // const name2 = intl.formatMessage(
  //   {
  //     id: 'component.myFavorites',
  //   },
  // );

  const [plist, setPlist] = useState([]);
  const [typelist, setTypelist] = useState([]);
  const [extAppslist, setExtAppslist] = useState([]);
  const [collectList, setCollectList] = useState([]);
  useEffect(() => { 
    // setName('liuyu');
    console.log('======useEffect======',initialState);
    clearCurrentTabList();
    const _list:any = [];
    initialState?.appList.map((_item:any) =>{
      const _prinfo = {
        code: _item.code,
        name: formatMessageWithDefault(`menu.${_item.code}`, _item.name),
        description: _item.description,
        background: _item.background || _item.icon,
        appType: _item.appType,
        appTypeName: _item.appTypeName,
        type: _item.type,
      }
      _list.push(_prinfo);
    });
    initialState?.extApps.map((_item:any) =>{
      const _prinfo = {
        code: _item.code,
        name: formatMessageWithDefault(`menu.${_item.code}`, _item.name),
        description: _item.description,
        background: _item.background || _item.icon,
        appType: _item.appType,
        appTypeName: _item.appTypeName,
        type: _item.type,
        href: _item.href,
      }
      _list.push(_prinfo);
    });
    // setExtAppslist(initialState?.extApps || [])
    _list.length &&  (setPlist(_list || []),fiterTypeList(_list));
    console.log('====_list====',_list);
    getCList();
    // const microApp = loadMicroApp({
    //   name: 'tcpi', // 唯一 id
    //   entry: '//localhost:3000/tcpi/', // html entry
    //   //   entry: 'http://test2.xhinkcar.cn/tcpi/', // html entry
    //   container: '#sub-app-tcpi',
    // });
    // microApp?.update?.({
    //   // microAppProps: {
    //   //   autoSetLoading: true,
    //   // },
    // });
    // return () => {
    //   microApp.unmount();
    // };

  }, []);

  const getCList = ()=>{
    getSysUserCollectList().then((res: any) => {
      if (res.appCode == 'S0000') {
        setCollectList(res.result || [])
      }
    });
  };

  const clickCollect = async (e:any,values:any)=>{
    console.log(values);
    e.stopPropagation();
    const _fl = collectList.find((_item:any)=> _item.sysCodeCollect == values.code);
    if(_fl){
      clickCloseCollect(_fl);
    }else{
      const hide = message.loading('');
      try {
        const _res = await sysUserCollect({sysCodeCollect:values.code});
        console.log(values,_res);
        if(_res.appCode == 'S0000'){
          message.success('成功');
          getCList();
        }else{
          message.error(_res.appMesg || '失败，请重试');
        }
        hide();
      } catch (error) {
        hide();
        message.error('失败，请重试');
      }
    }
    
  };
  const getAppBg= (_id:any)=>{
    let _img = '';
    plist.map((_item:any)=>{
      if(_item.code == _id){
        _img = _item.background;
        // _img = _item.type == '20' ?   _item.href : _item.background;
      }
    });
    return _img;
  };
  const getHeaderIcon= (_value:any)=>{
    let _txt = <HeartOutlined />
    // collectList
    const _fl = collectList.some((_item:any)=> _item.sysCodeCollect == _value.code);
    if(_fl){
      _txt = <HeartFilled  style={{color:"#FF0F00"}} />;
    }
    return _txt;
  };
  const clickCloseCollect = async (values:any)=>{
    const hide = message.loading('');
    try {
      const _res = await deletesysUserCollect({id:values.id});
      console.log(values,_res);
      if(_res.appCode == 'S0000'){
        message.success('成功');
        getCList();
      }else{
        message.error(_res.appMesg || '失败，请重试');
      }
      hide();
    } catch (error) {
      hide();
      message.error('失败，请重试');
    }
  };
  const gotoSystem = async (values:any,_type:any)=>{
    console.log(values);
    let _p = '';
    if(values.type == '10'){
      _p = values.code;
    }else if(values.type == '20'){
      let _url = values.href;
      _url.indexOf('?') != -1 ? _url=`${values.href}&token=${allToken}` : _url=`${values.href}?token=${allToken}`;
      window.open(_url);
    }else{
      _p = values.code;
    }
    // setInitialState((s:any) => ({ ...s, showMenu: true }));

    // history.push('/apphome/'+values.id);
    values.type != '20' && history.push('/'+_p+'/home');
  };
  const gotoCollectSystem = (values:any)=>{
    const _fl = plist.find((_item:any)=> _item.code == values.sysCodeCollect);
    if(_fl){
      gotoSystem(_fl,'all')
    }
  };
  const fiterTypeList = (values:any)=>{
    if(values.length){
      const _tl:any = [];
      values.map((_item:any)=>{
        const _fl = _tl.find((_i2:any)=> _i2.appType == _item.appType);
        if(_fl){
          _fl.list.push(_item);
        }else{
          const _info = {
            appType: _item.appType,
            appTypeName: _item.appTypeName,
            list:[_item]
          };
          _tl.push(_info);
        }
      });
      setTypelist(_tl);
    }
  };
  
  const searchApp =  (values:any)=>{
    if(values){
      const _dlist = plist
      .filter((_item:any) =>  {
        return (_item.name.toString().toUpperCase()).includes(values.toString().toUpperCase());
      });
      fiterTypeList(_dlist || []);
    }else{
      fiterTypeList(plist || []);
    }
  };
 
  const  formatMessageWithDefault =(id:any, defaultMessage:any, values = {})=> {  
    try {  
      // 尝试使用intl.formatMessage获取消息  
      return intl.formatMessage({ id, defaultMessage, ...values });  
    } catch (error) {  
      // 如果出现错误（这取决于你如何定义“错误”），则返回默认消息  
      return defaultMessage;  
    }  
  }  

  return (
    <Layout className={styles.container}>
      <div className={styles.container}>
          {/* <div id="sub-app-tcpi"></div> */}
        {/* <MicroApp name={'tcpi'} autoSetLoading  /> */}
        {/* <Carousel autoplay>
          <div>
            <h3 className={styles.tc_h_6}>1</h3>
          </div>
          <div>
            <h3 className={styles.tc_h_6}>2</h3>
          </div>
        </Carousel> */}
        {
          collectList.length ?  <h3 className={styles.tc_h_10}>{intl.formatMessage( { id: 'component.myFavorites'})} <span className={styles.tc_h_11}>({collectList.length})</span></h3>:""
        }
       
      {/* <Card title={name2}>
        <Card.Grid className={styles.tc_h_7}></Card.Grid>
          <Card.Grid hoverable={false} style={gridStyle}>
            Content
          </Card.Grid>
          <Card.Grid style={gridStyle}>Content</Card.Grid>
          <Card.Grid style={gridStyle}>Content</Card.Grid>
          <Card.Grid style={gridStyle}>Content</Card.Grid>
          <Card.Grid style={gridStyle}>Content</Card.Grid>
          <Card.Grid style={gridStyle}>Content</Card.Grid>
        </Card> */}
        <Row gutter={[16, 24]} className={styles.tc_h_9}>
          {
            collectList.length ? collectList.map((_item:any)=>{
              return (
                <Col
                  className="gutter-row"
                  key={'home_index_'+_item.id}
                  xs={4} sm={4} md={4} lg={4} xl={2}
                >
                  <Card bordered={false} hoverable className="tc_tcpi_1"  onClick={()=>gotoCollectSystem(_item)} >
                      <img alt="" src={getAppBg(_item.sysCodeCollect)} className={styles.tc_h_img1} />
                      <p className={styles.tc_tcpi_1_1}>
                        <Popover content={_item.sysCodeCollectName} placement="topLeft" >
                        {_item.sysCodeCollectName}
                        </Popover>
                      </p>
                    </Card>
                </Col>
              )
            }):
           ""
          }
        </Row>
        <div className={styles.tc_h_1}>
          {/* <h3 className={styles.tc_h_1_1}>{intl.formatMessage({ id: 'component.h_1'})}</h3> */}
          <Search 
          placeholder={intl.formatMessage( { id: 'component.globalHeader.search.app'})}
          enterButton={intl.formatMessage( { id: 'component.h_2'})} size="large" 
          style={{width:'30%',margin:'0 auto'}}
          onSearch={searchApp}
          />
        {/* <Input
            className={styles.tc_h_1_2}
            prefix={
              <SearchOutlined
                style={{
                  color: 'rgba(0, 0, 0, 0.15)',
                }}
              />
            }
            placeholder={intl.formatMessage( { id: 'component.globalHeader.search.app'})}
            // variant="borderless"
            onPressEnter={(e) => {
              searchApp((e.target as HTMLInputElement).value);
            }}
          /> */}
        </div>
        <Row gutter={[16, 24]}>
          {
            typelist.length ? typelist.map((_itpye:any)=>{
              return (
                <Col
                  className="gutter-row"
                  key={'home_app_type_'+_itpye.appType}
                  xs={12} sm={8} md={6} lg={6} xl={6}
                >
                  <div>
                    <h4 className={styles.tc_h_10} >{_itpye.appTypeName} <span className={styles.tc_h_11} >({_itpye.list.length})</span></h4>
                    {
                      _itpye.list.length ? _itpye.list.map((_item:any)=>{
                        return (
                          <Row
                          className={styles.tc_h_12}
                            key={'home_app_type_'+_item.appType}
                          >
                            <Card 
                              bordered={false} 
                              hoverable className="tc_home_t1"
                              onClick={()=>gotoSystem(_item,'all')}
                              // style={{backgroundImage:`url(${getAppBg(_item.name)})`}}
                              // cover={<img alt="" src={getAppBg(_item.name)} className="tc_home_t3" />}
                            >
                              <div className="tc_home_t1_1">
                                <img alt="" src={_item.background} className="tc_home_t3" />
                                {/* <p className="tc_home_t2">{intl.formatMessage( { id: `menu.${_item.name}`}) || _item.systemname} </p> */}
                                <div className="tc_home_t1_2">
                                  <p className="tc_home_t2">
                                    <Popover content={_item.name} placement="topLeft" >
                                      <span className={styles.tc_h_13}>{_item.name}</span> 
                                    </Popover>
                                    <span  className={styles.tc_h_14}>
                                    <Button  
                                    onClick={(e)=>clickCollect(e,_item)} 
                                    type='text' 
                                    icon={getHeaderIcon(_item)} />
                                    </span>
                                    </p>
                                  <p className={styles.tc_h_15}>
                                    <Popover content={_item.description} placement="topLeft" > {_item.description} </Popover>
                                    </p>
                                </div>
                                  {/* <p className={styles.tc_h_7}> <Button  onClick={()=>clickCollect(_item)}  icon={<HeartOutlined />} /></p> */}
                                  {/* <p ><Button onClick={()=>gotoSystem(_item,'all')}>{intl.formatMessage( { id: `menu.${_item.name}`}) || _item.systemname}</Button></p> */}
                              </div>
                                
                            </Card>
                          </Row>)}):""
                      }
                  </div>
                  
                  
                </Col>
              )
            }) :
            ""
          }
          {/* {
            extAppslist.length ? extAppslist.map((_item:any)=>{
              return (
                <Col
                  className="gutter-row"
                  key={'home_indexsystem_'+_item.id}
                  xs={12} sm={8} md={6} lg={6} xl={4}
                >
                  <Card 
                    bordered={false} 
                    hoverable className="tc_home_t1"
                    onClick={()=>gotoSystem(_item,'ext')}
                  >
                    <img alt="" src={_item.background} className="tc_home_t3" />
                    <p className="tc_home_t2">{formatMessageWithDefault(`menu.${_item.code}`, _item.name) } </p>
                  </Card>
                </Col>
              )
            }) :
           ""
          } */}

          {
            (!plist.length && !extAppslist.length) ? <Row className={styles.tc_h_8}>
            <Empty description={false}  />
          </Row>
          :''
          }
        </Row>
      {/* <div className={browserRedirect() ? styles.tc_h_2 : undefined}>     */}
      </div>
    </Layout>
  );
};

export default HomePage;
